package com.chenyue.cm.decrypt;

import com.chenyue.cm.common.utils.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author libingxing
 */
@Component
public class ParamDecodeResolver extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        ParamDecode annotation;
//        判断是否是方法
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(ParamDecode.class);
        } else {
            return true;
        }
//        判断方法是否带有加密注解
        if (annotation != null) {
//            EncodeUtils utils = new EncodeUtils("f2cb9dcb5c0ae0867a566cc8", "de200d9a22495787749b3a36");
            EncodeUtils utils = EncodeUtils.getInstance();
            String srcData = RequestUtil.getJsonString(request);
            System.err.println(srcData + "加密参数");
            //加密
            String encrypt = null;
            if (StringUtils.isNotBlank(srcData)) {
                try {
                    encrypt = utils.encrypt(srcData);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                request.setAttribute("param", encrypt);
            }
        }

        return true;
    }

}
